<template>
  <div class="password-form">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      size="large"
      @keyup.enter="login(ruleFormRef)"
    >
      <el-form-item prop="username">
        <el-input
          v-model="ruleForm.username"
          prefix-icon="user"
          clearable
          :placeholder="$t('login.userError')"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          prefix-icon="lock"
          clearable
          show-password
          :placeholder="$t('login.PWPlaceholder')"
        />
      </el-form-item>
      <el-form-item>
        <div class="box-code">
          <el-input
            v-model="ruleForm.captcha"
            prefix-icon="CircleCheck"
            clearable
            placeholder="请输入验证码"
          />
          <el-image class="code-image" :src="captchaUrl" @click="getCaptcha" />
        </div>
      </el-form-item>
      <div class="remember">
        <div>
          <el-checkbox disabled label="记住密码"></el-checkbox>
        </div>
        <div>
          <router-link to="">忘记密码？</router-link>
        </div>
      </div>
      <el-form-item>
        <el-button
          type="primary"
          round
          style="width: 100%"
          :loading="isLogin"
          @click="login(ruleFormRef)"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onBeforeMount } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { captchaImage, loginByJson } from '@api/login'
import { Encrypt } from '@utils/aes'
import { UserRuleForm } from '@interface/login'
import { useI18n } from 'vue-i18n'
import useLogin from '@hooks/useLogin'

const { t } = useI18n()

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<UserRuleForm>({
  username: 'admin',
  password: 'abc123456',
  key: '',
  captcha: ''
})

const rules = reactive<FormRules<UserRuleForm>>({
  username: [{ required: true, message: t('login.userError'), trigger: 'blur' }],
  password: [{ required: true, message: t('login.PWPlaceholder'), trigger: 'blur' }]
})

// 验证码
const captchaUrl = ref<string>()

// 加载状态
const isLogin = ref<boolean>(false)

const getCaptcha = async () => {
  // 当前时间的时间戳
  const key: string = new Date().getTime().toString()
  ruleForm.key = key
  // 获取图形验证码
  const res = await captchaImage({ key })
  // 解析为图片
  const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
  const imageUrl = URL.createObjectURL(blob)
  captchaUrl.value = imageUrl
}

onBeforeMount(() => {
  getCaptcha()
})

// 登录
const login = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      isLogin.value = true
      const res = await loginByJson({
        username: Encrypt(ruleForm.username),
        password: Encrypt(ruleForm.password),
        key: ruleForm.key,
        captcha: ruleForm.captcha
      })
      isLogin.value = false
      if (res.code !== '200') {
        ElMessage.error(res.msg)
      }

      // 登录 hooks
      useLogin(res)
    } else {
      ElMessage.warning('请填写正确内容')
    }
  })
}
</script>

<style lang="less" scoped>
.password-form {
  .remember {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .box-code {
    display: flex;
    align-items: center;
    width: 100%;

    .code-image {
      margin-left: 10px;
      width: 100px;
      height: 40px;
      cursor: pointer;
    }
  }
}
</style>
